package com.smarthospital.dao.im.daoService.impl;

import com.smarthospital.dao.im.dao.IMMessageDao;
import com.smarthospital.dao.im.daoService.IMMessageDaoService;
import com.smarthospital.entity.im.IMMessage;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQueryBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Iterator;

/**
 * create by sym  2021/5/9 21:20.
 */
@Slf4j
@Service
public class IMMessageDaoServiceImpl implements IMMessageDaoService {
    @Autowired
    private IMMessageDao imMessageDao;

    @Autowired
    private ElasticsearchRestTemplate template;


    @Override
    public Page<IMMessage> getByOrderId(String orderId, Integer pageNum, Integer pageSize) {
        //排序构建
        TermQueryBuilder query = QueryBuilders.termQuery("orderId", orderId);
        PageRequest request = PageRequest.of(pageNum, pageSize, Sort.by(Sort.Direction.DESC, "timeStamp"));
        Page<IMMessage> search = imMessageDao.search(query, request);
        return search;
    }

    @Override
    public void save(IMMessage imMessage) {
        imMessageDao.save(imMessage);

    }

    @Override
    public void deleteAll(){
        imMessageDao.deleteAll();
    }

    /**
     * 条件查询：根据传入消息的id、发送者 、订单号、接收者 查询历史消息
     * 循环更新
     */
    @Override
    public void messageschangeToReaded(IMMessage imMessage){

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("orderId",imMessage.getOrderId()));
        boolQueryBuilder.must(QueryBuilders.matchQuery("senderId",imMessage.getReceiverId()));
        boolQueryBuilder.must(QueryBuilders.matchQuery("receiverId",imMessage.getSenderId()));

        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("timeStamp").lte(System.currentTimeMillis());
        boolQueryBuilder.filter(rangeQueryBuilder);
        Iterable<IMMessage> search1 = imMessageDao.search(boolQueryBuilder);
        Iterator<IMMessage> iterator = search1.iterator();
        while (iterator.hasNext()) {
            IMMessage next = iterator.next();
            if (next.getStatus() == 0) {
                updateStatusById(next.getId());
            }
        }
    }

    /**
     * 根据id将消息状态置为已读
     * @param id
     */
    private void updateStatusById(String id) {
        UpdateRequest updateRequest = new UpdateRequest("immessage","immessage", id);
        try {
            XContentBuilder staus = JsonXContent.contentBuilder().startObject().field("status", 1).endObject();
            updateRequest.doc(staus);
        } catch (IOException e) {
            log.error("【消息设置为已读】 err {}",e.getMessage(),e);
        }

        //根据id修改状态
        UpdateQuery build = new UpdateQueryBuilder()
                .withIndexName("immessage")
                .withType("immessage")
                .withId(id)
                .withUpdateRequest(updateRequest)
                .build();

        try {
            template.update(build);
        } catch (Exception e) {
            log.error("【消息设置为已读】 update err {}",e.getMessage(),e);
        }
    }

}
